<template>
  <div>
    <el-card class="sun-el-card">
      <sunUpdataAdd :title="this.$route.meta.title" :tab-list-right="tabListRight" :tab-list="tabList" :show-adddata="false" />
      <el-table
        v-loading="listLoading"
        :data="list"
        element-loading-text="Loading"
        border
        fit
        highlight-current-row
        row-key="key"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        :header-cell-style="{color:'#000000'}"
      >
        <el-table-column label="KEY" prop="key" width="150" />
        <el-table-column label="字段名称" prop="name" />
        <el-table-column align="center" label="学年学期">
          <template slot-scope="{row}">
            <span>{{ row.acad_year_term.acad_year_term_name }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="必填">
          <template slot-scope="{row}">
            <span>{{ row.required ? '是' : '否' }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="状态">
          <template slot-scope="{row}">
            <span>{{ row.enable ? '启用' : '禁用' }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="排序" prop="displayorder" />
        <el-table-column align="center" label="操作" width="190">
          <template slot-scope="{row}">
            <el-button :disabled="row.category !== 'group'" :type="row.category === 'group' ? 'primary' : 'info'" size="mini" @click="groupAdd(row.key)">
              <i class="el-icon-plus" />
              字 段
            </el-button>
            <el-button type="primary" size="mini" @click="showEditList(row)">
              <i class="el-icon-edit" />
              编 辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-drawer
      class="sun-el-drawer"
      :with-header="false"
      :destroy-on-close="true"
      :wrapper-closable="false"
      :visible.sync="show_addList"
      direction="rtl"
    >
      <addList :name="add_title" :data-list="dataList" :form-data="formData" />
    </el-drawer>
    <el-drawer
      ref="edit"
      class="sun-el-drawer"
      :with-header="false"
      :destroy-on-close="true"
      :wrapper-closable="false"
      :visible.sync="show_editList"
      direction="rtl"
    >
      <editList ref="editList" name="编辑" :data-list="dataList" :form-data="formData" :ob-jexf-value="obJexfValue" />
    </el-drawer>
  </div>
</template>

<script>
import { get, put, post } from '@/api/request'
import { $remove, $tooltips } from '@/sun-components/SunMsg.js'
import SunUpdataAdd from '@/sun-components/SunUpdataAdd'

import AddList from './components/addList'
import EditList from './components/editList'

export default {
  name: 'DataBank',
  components: { /** SunSearch, */ SunUpdataAdd, AddList, EditList },
  data() {
    return {
      tabList: [
        { id: 1, old_id: 1, name: '课程评价', value: 'old', type: 'primary' },
        { id: 2, old_id: 1, name: '课程准入', value: 'new', type: 'mini' }
      ],
      tabItem: {},
      tabListRight: [
        { id: 1, old_id: 1, name: '字段', value: 'field', icon: 'el-icon-plus', type: 'primary' },
        { id: 2, old_id: 1, name: '分组', value: 'group', icon: 'el-icon-plus', type: 'primary' }
      ],
      searchList: [],
      searchFilter: {},
      list: [],
      listLoading: true,
      show_addList: false,
      show_editList: false,
      add_title: '',
      defaultArray: [],
      modelList: [],
      dataList: [],
      formData: {},
      category: '',
      edit_id: 0,
      obJexfValue: {},
      groupKey: ''
    }
  },
  created() {
    this.tabItem = this.tabList[0]
    this.upData()
    this.getinformation()
  },
  methods: {
    upData() {
      this.requestData()
    },
    async showEditList(row) {
      const _that = this
      if (row.category === 'field') {
        if (row.exf && row.exf.constructor !== Object) {
          this.obJexfValue = {
            'imgValue': [],
            'zipValue': [],
            'fileValue': [],
            'videoValue': [],
            'audioValue': []
          }
        } else {
          this.obJexfValue = row.exf
        }
      }
      if (row.parent_id && row.parent_key) {
        _that.groupKey = row.parent_key
        _that.edit_id = row.parent_id
      } else {
        _that.groupKey = false
        _that.edit_id = row.id
      }
      _that.category = row.category
      _that.dataList = _that.modelList[row.category]
      _that.formData = _that.modelList[row.category + '_formData']
      for (const key in row) {
        if (key === 'id' || key === 'acad_year_term' || key === 'parent_id' || key === 'parent_key') {
          // ('不需要')
        } else {
          // _that.formData[key] = row[key]
          _that.$set(_that.formData, key, row[key])
        }
      }
      _that.dataList?.forEach((item) => {
        if (item.key !== 'permission' && item.options) {
          item.options?.forEach((el) => {
            if (_that.formData[item.key] === el.key) {
              el.checked = true
              if (el.attribute) {
                el.attribute?.forEach((e) => {
                  el[item.key + '_' + el.key][e.key] = _that.formData[e.key]
                  delete _that.formData[e.key]
                })
              }
            }
          })
        }
      })
      _that.show_editList = true
    },
    async drawerClose(type) {
      this[type] = false
    },
    async groupAdd(row_key) {
      const _that = this
      _that.category = 'field'
      _that.dataList = _that.modelList[_that.category]
      _that.formData = _that.modelList[_that.category + '_formData']
      _that.groupKey = row_key
      _that.add_title = '添加字段'
      _that.edit_id = 0
      Object.getOwnPropertyNames(_that.formData)?.forEach(function(key) {
        if (_that.formData[key] === null) return
        if (key !== 'category') {
          // String 类型
          if (_that.formData[key].constructor === String) {
            _that.formData[key] = ''
          }
          if (_that.formData[key].constructor === Number) {
            // eslint-disable-next-line no-prototype-builtins
            if (_that.defaultArray.hasOwnProperty(key)) {
              _that.formData[key] = _that.defaultArray[key]
            } else {
              _that.formData[key] = 1
            }
          }
          // Array 类型
          if (_that.formData[key].constructor === Array) {
            _that.formData[key] = []
            return
          }
          // Object 类型
          if (_that.formData[key].constructor === Object) {
            _that.formData[key] = {}
          }
          // Boolean 类型
          if (_that.formData[key].constructor === Boolean) {
            _that.formData[key] = false
          }
        }
      })
      _that.show_addList = true
    },
    async tabHeaderBtn(id) {
      const _that = this
      _that.groupKey = false
      _that.edit_id = 0
      _that.tabListRight?.forEach((item) => {
        if (item.id === id) {
          _that.category = item.value
          _that.dataList = _that.modelList[item.value]
          _that.formData = _that.modelList[item.value + '_formData']
          if (item.value === 'group') {
            _that.add_title = '添加分组'
          } else if (item.value === 'field') {
            _that.add_title = '添加字段'
          }
          Object.getOwnPropertyNames(_that.formData)?.forEach(function(key) {
            if (_that.formData[key] === null) return
            if (key !== 'category') {
              // String 类型
              if (_that.formData[key].constructor === String) {
                _that.formData[key] = ''
              }
              // Number 类型
              if (_that.formData[key].constructor === Number) {
                // eslint-disable-next-line no-prototype-builtins
                if (_that.defaultArray.hasOwnProperty(key)) {
                  _that.formData[key] = _that.defaultArray[key]
                } else {
                  _that.formData[key] = 1
                }
              }
              // Array 类型
              if (_that.formData[key].constructor === Array) {
                _that.formData[key] = []
                return
              }
              // Object 类型
              if (_that.formData[key].constructor === Object) {
                _that.formData[key] = {}
              }
              // Boolean 类型
              if (_that.formData[key].constructor === Boolean) {
                _that.formData[key] = false
              }
            }
          })
          console.log(_that.formData)
          _that.show_addList = true
        }
      })
    },
    async tabHeaderSelect(id) {
      const _that = this
      _that.tabList?.forEach((item) => {
        if (item.old_id === id) {
          return false
        }
        if (item.id === id) {
          item.type = 'primary'
          _that.tabItem = item
          _that.upData()
        } else {
          item.type = 'mini'
        }
        item.old_id = id
      })
    },
    async searchResult(filter) {
      this.searchFilter = filter
      this.upData()
    },
    async removeData(id) {
      $remove(`course/evaluation/setting/information/categories/${id}`, this)
    },
    async onFinish() {
      const _that = this
      if (_that.formData.name === '') {
        $tooltips('请填写名称')
        return
      }
      if (_that.formData.category === 'field') { // 添加或者编辑字段
        if (_that.formData.type === '') {
          $tooltips('请填选择字段类型')
          return
        }
        if (_that.formData.type === 'file' || _that.formData.type === 'files') {
          if (!_that.formData.exf) {
            $tooltips('请选择文件后缀')
            return
          }
        }
      }
      // _that.$onFinishBox().then((action) => {
      //   if (action) {
      if (_that.edit_id) {
        put(`course/evaluation/setting/information/categories/${_that.edit_id}` + '?evaluation_type=' + _that.tabItem.value, { key: _that.formData.key, course_evaluation_information_category: _that.formData }).then(response => {
          if (response.code === 0) {
            _that.dataList = []
            _that.formData = {}
            _that.drawerClose('show_editList')
            _that.upData()
          }
        })
      } else {
        const group = _that.groupKey ? { group: _that.groupKey } : {}
        post(`course/evaluation/setting/information/categories?evaluation_type=` + _that.tabItem.value,
          { course_evaluation_information_category: _that.formData, category: _that.category, ...group })
          .then(response => {
            if (response.code === 0) {
              _that.dataList = []
              _that.formData = {}
              _that.drawerClose('show_addList')
              _that.upData()
            }
          })
      }
      // }
      // })
      // .catch((cancel) => {
      //   // 点击取消
      // })
    },
    async requestData() {
      this.listLoading = true
      await get(`course/evaluation/setting/information/categories?evaluation_type=` + this.tabItem.value, this.searchFilter).then(response => {
        if (response.code === 0) {
          response.data?.forEach((item) => {
            if (item.children) {
              item.children?.forEach((el) => {
                el['parent_id'] = item.id
              })
            }
          })
          this.list = response.data
        }
        this.listLoading = false
      })
    },
    async getinformation() {
      const _that = this
      await get(`course/evaluation/setting/information/model`).then(response => {
        if (response.code === 0) {
          // formData 必须提前准备点击弹框时创建会渲染错误
          Object.keys(response.data)?.forEach((item) => {
            response.data[item + '_formData'] = { category: item }
            response.data[item]?.forEach((el) => {
              // eslint-disable-next-line no-prototype-builtins
              if (el.hasOwnProperty('default')) {
                Object.assign(_that.defaultArray, { [el.key]: el.default })
              }
              response.data[item + '_formData'][el.key] = el.type === 'checkBox' ? [] : el.type === 'number' ? 0 : el.type === 'radio' ? 1 : ''
              if (el.options && el.key !== 'permission') {
                el.options?.forEach((eloptions) => {
                  // eslint-disable-next-line no-prototype-builtins
                  if (eloptions.hasOwnProperty('default')) {
                    Object.assign(_that.defaultArray, { [eloptions.key]: eloptions.default })
                  }
                  eloptions[el.key + '_' + eloptions.key] = {}
                  if (eloptions.attribute) {
                    eloptions.attribute?.forEach((e) => {
                      // eslint-disable-next-line no-prototype-builtins
                      if (e.hasOwnProperty('default')) {
                        Object.assign(_that.defaultArray, { [e.key]: e.default })
                      }
                      eloptions[el.key + '_' + eloptions.key][e.key] = e.type === 'checkBox' ? [] : e.type === 'number' ? 0 : e.type === 'radio' ? 1 : ''
                      eloptions['checked'] = false
                    })
                  }
                })
              }
            })
          })
          this.$set(this.formData, 'defaultArray', _that.defaultArray)
          this.modelList = response.data
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
  @import '@/styles/sun-style.scss';
</style>
